import json
import random
import time
from time import sleep

import allure
import ddddocr
from selenium import webdriver
from selenium.webdriver.common.by import By

from common.commin.commin import read_ini
from common.log.log import log
from common.request.request_api import RequestHandler
from config.conf import BASE_DIR, JH_USERNAME, JH_PASSWORD

# 环境地址
yg_url = read_ini(BASE_DIR + '/config_yg.ini')['host']['url']


@allure.step('金花商城后台-商品管理-仓库中商品查询')
def api_search_store_product_type(drive, keyword, type_num):
    """
    金花商城后台-商品管理-按类型搜索商品
    keyword： 搜索词
    type_num：类型  1：出售中商品； 2：仓库中商品； 3：已经售馨商品；4：警戒库存；5：商品回收站
    return 查询的数据
    """
    try:
        log.info('金花商城后台-商品管理-按类型搜索商品')
        token = drive.get_cookies()[0]['value']
        req = RequestHandler(token, 'yg')
        get_url = yg_url + f'/jinhua/api/admin/store/product/list?page=1&limit=20&cateId=&keywords={keyword}&type={type_num}&isVip=0&temp=1668506756'
        response = req.visit('get', get_url)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(1)
        return response.text
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-商品管理-仓库中商品查询，出现异常为：{e}')
        raise e


@allure.step('金花商城后台-订单-发货')
def api_deliver_goods(drive, order_no):
    """
    金花商城后台-订单-发货
    """
    try:
        log.info('api接口——金花商城后台-订单-发货')
        token = drive.get_cookies()[0]['value']
        req = RequestHandler(token, 'yg')
        get_url = yg_url.split('.com')[
                      0] + '.com' + f'/jinhua/api/admin/store/order/send'

        """
        发送货增加了deliverGoods，先获取 "goodsId" 订单商品的ID   
        【查询订单详情的接口】
        """
        get_goods = yg_url + f'/jinhua/api/admin/store/order/info?orderNo={order_no}&temp=1678068452'
        response_goods = req.visit('get', get_goods)
        result_dict_dict = json.loads(response_goods.text)  # 将返回的response.text str转换为dict
        log.info(result_dict_dict)
        goods_id = result_dict_dict['data']['orderInfo'][0]['id']  # 商品的ID
        express_number = random.randint(100000000, 999999999)  # 发货订单随机数
        json_data = {
            "type": "1",
            "expressRecordType": "1",
            "expressId": "",
            "expressCode": "zhiguil",
            "deliveryName": "",
            "deliveryTel": "",
            "expressNumber": express_number,
            "expressTempId": "",
            "toAddr": "深圳福田",
            "toName": "花王云购",
            "toTel": "99999999999",
            "orderNo": order_no,
            "deliverGoods": [{"count": "1", "goodsId": goods_id, "isGift": False}]
        }
        response = req.visit('post', get_url, json=json_data)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(1)
        return response.text
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-订单-发货，出现异常为：{e}')
        raise e


@allure.step('金花商城后台-订单-搜索订单')
def api_search_orders(drive, time, keyword):
    """
    金花商城后台-订单-发货
    time: 今天：today  昨天：yesterday  最近7天：lately7  最近30天：lately30  本月：month  本年：year
    keyword: 搜索关键词（支持：请输入订单号/下单人手机号/收货人手机号）
    """
    try:
        log.info('api接口——金花商城后台-订单-搜索订单')
        token = drive.get_cookies()[0]['value']
        req = RequestHandler(token, 'yg')
        get_url = yg_url + f'/jinhua/api/admin/store/order/list?status=all&dateLimit={time}&keywords={keyword}&page=1&limit=20&type=&isVip=&temp=1671178231'
        response = req.visit('get', get_url)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(1)
        return response.text
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-订单-搜索订单，出现异常为：{e}')
        raise e


@allure.step('金花商城后台-新增敏感词')
def api_add_sensitive(token, keyword):
    """
    金花商城后台-新增敏感词
    """
    try:
        log.info('api接口——金花商城后台-新增敏感词')
        req = RequestHandler(token, 'yg')
        json_data = {
            "text": keyword,
            "type": 1
        }
        get_url = yg_url + f'/jinhua/api/admin/sensitive/save'
        response = req.visit('post', get_url, json=json_data)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(1)
        return response.text
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-新增敏感词，出现异常为：{e}')
        raise e


@allure.step('金花商城后台-获取待发货商品id')
def get_goods_id(token, order_id):
    """
    金花商城后台-获取待发货商品id
    """
    try:
        log.info('api接口——金花商城后台-获取待发货商品id')
        req = RequestHandler(token, 'yg')

        get_url = yg_url + f'/jinhua/api/admin/store/order/getGoodsToBeShipped?orderNo={order_id}&temp=1691483459'
        response = req.visit('get', get_url)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(1)
        log.info(response.text)
        goods_id = json.loads(response.text)['data'][0]['id']
        log.info(goods_id)
        return goods_id
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-获取待发货商品id，出现异常为：{e}')
        raise e


@allure.step('金花商城后台-发货')
def ht_api_send(token, order_id, count):
    """
    金花商城后台-发货
    order_id：订单ID
    goods_id：商品ID
    count：商品数
    """
    try:
        log.info('api接口——金花商城后台-发货')
        goods_id = get_goods_id(token, order_id)
        req = RequestHandler(token, 'yg')
        json_data = {
            "type": "1",
            "expressRecordType": "1",
            "expressId": "",
            "expressCode": "yoseus",
            "deliveryName": "",
            "deliveryTel": "",
            "expressNumber": "454353453",
            "expressTempId": "",
            "expressTime": "",
            "toAddr": "深圳福田",
            "toName": "花王云购",
            "toTel": "99999999999",
            "orderNo": order_id,
            "deliverGoods": [{
                "count": count,
                "goodsId": goods_id,
                "isGift": False
            }]}
        get_url = yg_url + f'/jinhua/api/admin/store/order/send'
        response = req.visit('post', get_url, json=json_data)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(2)
        log.info(response.text)
        return response.text
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-发货，出现异常为：{e}')
        raise e


@allure.step('金花商城后台-查询用户')
def api_search_user(token, key, iPhone='18665825382', mode='yg'):
    """
    金花商城后台-查询并返回用户指定的值
    """
    try:
        _yg_url = read_ini(BASE_DIR + '/config_yg.ini')['host']['url']
        yc_url = read_ini(BASE_DIR + '/config_yc.ini')['host']['url']
        log.info('api接口——金花商城后台-查询用户')
        if mode == 'yc':
            _yg_url = yc_url
        referer = _yg_url + '/admin/user/index'
        req = RequestHandler(token, 'yght', referer)
        get_url = _yg_url + f'/jinhua/api/admin/user/list?labelId=&userType=&sex=&isPromoter=&country=&payCount=&accessType=0&dateLimit=&keywords={iPhone}&province=&city=&page=1&limit=20&level=&groupId=&isPartner=&temp=1691142226'
        response = req.visit('get', get_url)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        user_info = response.text
        if key == 'nowMoney':
            now_money = json.loads(user_info)['data']['list'][0]['nowMoney']
            return now_money
        elif key == '':
            pass
        elif key == '':
            pass
        elif key == '':
            pass
        elif key == '':
            pass
        elif key == '':
            pass
        elif key == '':
            pass
        elif key == '':
            pass

    except Exception as e:
        log.error(f'API接口异常：金花商城后台-查询用户，出现异常为：{e}')
        raise e


@allure.step('金花商城后台-用户管理，编辑用户等级')
def api_edit_user_level(drive, level):
    """
    金花商城后台-用户管理，编辑用户等级
    iphone_number: 用户手机号
    lever: 1：普通会员，2：VIP会员，3：合伙人
    """
    try:
        log.info('api接口——金花商城后台-用户管理，编辑用户等级')
        # 数据库根据手机号查出ID
        # 暂时无法实现，要成功查sql都要确保SVN已连接，先写死：18665825382 --> 39151
        memer_id = ''
        token = drive.get_cookies()[0]['value']
        req = RequestHandler(token, 'yg')
        json_data = {
            "id": 39151,
            "mark": "",
            "status": 'true',
            "addres": "9999",
            "groupId": "",
            "level": level,
            "isPromoter": 'false',
            "tagId": "",
            "isStaff": 'false'}
        get_url = yg_url + f'/jinhua/api/admin/user/update?id=39151'
        response = req.visit('post', get_url, json=json_data)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(1)
        return response.text
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-订单-搜索订单，出现异常为：{e}')
        raise e


""" 调试必须要 """


def login_ht_demo():
    log.info('登录金花商城后台')
    # 清空数据
    allure_results = BASE_DIR + '\\allure-results'
    # del_files(allure_results)
    # 获取config.ini环境地址
    env = read_ini()['host']['url']
    """
    设置chrome浏览器无界面模式
    """
    # chrome_options = Options()
    # chrome_options.add_argument("--headless")
    # drive = webdriver.Chrome(options=chrome_options)

    global driver_chrome  # 全局变量，方便失败操作的钩子函数 调用 drive，进行截图
    driver_chrome = webdriver.Chrome()
    driver_chrome.implicitly_wait(15)
    driver_chrome.delete_all_cookies()  # 为了防止污染，清空cookie
    driver_chrome.get(env)
    driver_chrome.maximize_window()

    driver_chrome.find_element(By.CSS_SELECTOR, '[name="username"]').send_keys(JH_USERNAME)
    driver_chrome.find_element(By.CSS_SELECTOR, '[name="pwd"]').send_keys(JH_PASSWORD)

    retry_count = 20  # 定义重试次数
    count = 0
    for i in range(retry_count):
        # 处理验证码
        code_file = BASE_DIR + '/data/code.png'
        img = driver_chrome.find_element(By.CSS_SELECTOR, ".imgs")  # 验证码图片
        img.screenshot(code_file)  # 下载图片
        # 利用ddddocr识别验证码
        ocr = ddddocr.DdddOcr(show_ad=False)  # show_ad 不打印广告了
        with open(code_file, "rb") as fp:
            image = fp.read()
        result = ocr.classification(image)  # 返回验证码识别结果
        log.info("=============================")
        log.info(result)

        sel = driver_chrome.find_elements(By.CSS_SELECTOR, '.el-input__inner')
        sel[-1].clear()
        sel[-1].send_keys(result)
        driver_chrome.find_element(By.CSS_SELECTOR, '.el-button--medium').click()
        time.sleep(1)

        success_url = driver_chrome.current_url
        count += 1
        if 'login' not in success_url:
            log.info('登录成功')
            time.sleep(3)
            break
        if count == retry_count:
            log.error(f'尝试了{retry_count}次获取验证码仍然失败，请重新检查复杂度！')
            raise
    return driver_chrome


@allure.step('金花商城后台-发送1张赠送券')
def ht_api_send_coupons(token, member_id='39151', coupons_id='31601'):
    """
    金花商城后台-发送1张赠送券
    coupons_id,  # 优惠券ID，固定为：自动化测试永久存在勿删
    member_id  # 固定测试账号
    """
    try:
        log.info('api接口——金花商城后台-发送1张赠送券')
        req = RequestHandler(token, 'yg')
        get_url = yg_url + f'/jinhua/api/admin/marketing/coupon/user/receive?couponId={coupons_id}&uid={member_id}'
        response = req.visit('post', get_url)
        allure.attach(body=response.text, name="接口请求响应json", attachment_type=allure.attachment_type.JSON)
        sleep(2)
        log.info(response.text)
        return response.text
    except Exception as e:
        log.error(f'API接口异常：金花商城后台-发送1张赠送券，出现异常为：{e}')
        raise e


if __name__ == '__main__':
    # drive = login_ht_demo()  # 调试用，获取后台token
    # result = api_edit_user_level(drive, '1')  # 编辑用户等级为普通会员
    # log.info(result)
    # drive.close()

    # 发货调试
    drive = login_ht_demo()  # 调试用，获取后台token
    result = api_deliver_goods(drive, 'order167806945697016079')  # 订单发货
    log.info(result)
    drive.close()
